package com.ziytek.web.citizen.model.bean;

import com.ziytek.web.citizen.constant.ServerConstant;
import com.ziytek.web.citizen.util.HexUtil;
import com.ziytek.web.citizen.util.StringUtil;
import lombok.Data;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author fenghx
 * @version v1.0
 * @className LightControl
 * @descripton 功能描述
 * @date 2023/7/12 13:46
 **/

@Data
public class LightControl {
    /***
     * 分控版地址
     * */
    private String controlAddress;
    /***
     * 电芯位置
     * */
    private String cellPosition;

    /***
     * 灯控状态 1-亮灯 0- 灭灯
     * */
    private String lightControlStatus;

    public List<LightControl> lightControlSettingSetInit(List<LightControl> lightControls, String status) {
        List<String> list = Arrays.asList("10", "20", "40", "80");
        List<LightControl> controls = new ArrayList<>();
        list.forEach(s -> {
            for (int i = ServerConstant.DATA_COUNT_ZERO; i < ServerConstant.CHARGE_CONTROL_PROTOCOL_DATA_LENGTH; i++) {
                int controlNum = HexUtil.hexToInt(s) + i;
                String controlAddress = HexUtil.intToHex(controlNum);
                for (int y = ServerConstant.PAGE_NUM_START; y <= ServerConstant.BATTERY_NUM; y++) {
                    LightControl lc = new LightControl();
                    lc.setControlAddress(controlAddress);
                    lc.setCellPosition(String.valueOf(y));
                    if (anyMatch(lightControls, controlAddress, String.valueOf(y))) {
                        lc.setLightControlStatus(status);
                    } else {
                        lc.setLightControlStatus(ServerConstant.LIGHT_CONTROL_STATUS_CLOSE);
                    }
                    controls.add(lc);
                }
            }
        });
        return controls;
    }


    private boolean anyMatch(List<LightControl> lightControls, String controlAddress, String position) {
        if (CollectionUtils.isEmpty(lightControls) || StringUtil.isEmpty(controlAddress) || StringUtil.isEmpty(position)) {
            return false;
        }
        return lightControls.stream().anyMatch(t -> t.getControlAddress().equalsIgnoreCase(controlAddress) && t.getCellPosition().equalsIgnoreCase(position));
    }
}
